package com.paul.web.handler;

import com.paul.common.exception.BusinessException;
import com.paul.common.exception.ExceptionCode;
import com.paul.common.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：zmk
 * @date ：Created in 2021/11/11 10:34
 * @description：IP拦截器
 */
@Slf4j
public class IPInterceptor implements HandlerInterceptor {

    private String[] serviceIps = {};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤ip,若用户在白名单内，则放行
        String ipAddress = IpUtil.getIpAddr(request);
        String path = request.getServletPath();
        log.info("Specify the IP access interface =>" + ipAddress + "   ||   " + path);
        if (!StringUtils.isNotBlank(ipAddress))
            return false;
        if (!ArrayUtils.contains(serviceIps, ipAddress)) {
            return true;
        }

        throw new BusinessException(ExceptionCode.REPEATED_REQUESTS.value(), "非白名单，拒绝访问");
//        response.getWriter().append("<h1 style=\"text-align:center;\">Not allowed!</h1>");
//        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
